<template>
  <div>
    <AuFormModal
      ref="formRef"
      v-model="showModal"
      :title="t('device_update.modal.title')"
      :formList="formList"
      :formData="selfFormData"
      :modalProps="{
        width: 600,
        height: '80vh',
        position: 'center'
      }"
      :formProps="{
        labelWidth: 80,
        class: '!w-[486px]'
      }"
      @formChange="formChange"
      @handleConfirm="handleConfirm"
    >
      <template #link_behind>
        <!--        <el-button type="primary" @click="showPost"> 新建岗位</el-button>-->
        <div class="flex items-end">
          <el-upload
            :show-file-list="false"
            class="upload-empDocs w-[24%]"
            action="/autata/file/upload"
            :data="{ foldername: 'softwareUpgrade' }"
            accept="application/vnd.android.package-archive,ipa"
            :before-upload="beforeUpload"
            @progress="onProgress"
            @success="e => onSuccess(e)"
            @error="onError"
          >
            <div v-loading="loading" class="w-full h-full">
              <img v-if="apkLink" :src="ZipShowImg" class="h-full" alt="" />
              <div v-else class="text-center mt-[50%] translate-y-[-50%]">
                <FontIcon icon="icon-upload" />
              </div>
            </div>
          </el-upload>
          <div v-if="versionName" class="text-[--autata-font-gray-color] ml-2">
            v{{ versionName }}
          </div>
        </div>
      </template>

      <template #upgrade_type_behind>
        <vxe-radio-group v-model="selfFormData.upgrade_type" :strict="false">
          <vxe-radio
            :label="2"
            :content="t('device_update.form.force_upgrade')"
          />
          <vxe-radio
            :label="1"
            :content="t('device_update.form.prompt_upgrade')"
          />
          <vxe-radio
            :label="0"
            :content="t('device_update.form.default_upgrade')"
          />
        </vxe-radio-group>
      </template>
      <template #use_test_behind>
        <vxe-radio-group v-model="selfFormData.use_test" :strict="false">
          <vxe-radio :label="1" :content="t('device_update.yes')" />
          <vxe-radio :label="2" :content="t('device_update.no')" />
        </vxe-radio-group>
      </template>
    </AuFormModal>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, toRef, watch } from "vue";
import { AuFormModal } from "@/components/AuModal";
import { cloneDeep, omit } from "lodash-unified";
import {
  softwareUpgradeAdd,
  SoftwareUpgradeListProps,
  softwareUpgradeUpdate
} from "@/api/factory/device";
import { businessGetList } from "@/api/factory/business";
import ZipShowImg from "@/assets/zip_show.png";
import { FORM_LIST, SOFTWARE_TYPES } from "./constant";
import { ResultProps } from "@/api/user";
import {
  ElMessage,
  UploadFile,
  UploadFiles,
  UploadProgressEvent,
  UploadProps
} from "element-plus";
import { getBoardVersions } from "@/api/cabinet/device";
import { isArray } from "@pureadmin/utils";
import { useI18n } from "vue-i18n";

interface Props {
  modelValue: boolean;
  formData?: Partial<{
    version_name: string;
    upgrade_type?: number;
    use_test?: number;
  }>;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
});
const emit = defineEmits(["update:modelValue", "submit"]);

const { t } = useI18n();

const title = ref(t("device_update.modal.title"));
const apkLink = ref("");
const versionName = ref("");
const loading = ref(false);
const formList = ref(FORM_LIST);
const selfFormData = ref({
  version_name: "",
  upgrade_type: 0,
  use_test: 2
});
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(val: boolean) {
    emit("update:modelValue", val);
  }
});
const isForce = ref();

const formRef = ref();

// region ====================================事件的集合
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  // if (rawFile.type !== "application/vnd.android.package-archive") {
  //   ElMessage.error("请选择后缀为 apk 的文件类型");
  //   return false;
  // } else
  if (rawFile.size / 1024 / 1024 > 500) {
    ElMessage.error(t("device_update.file_too_large"));
    return false;
  }
  return true;
};

const onProgress = (
  event: UploadProgressEvent,
  file: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(event);
  loading.value = true;
};

const onSuccess = (
  file: ResultProps<{
    relative_path: string;
    path: string;
    size: number;
    versionName: string;
  }>
) => {
  loading.value = false;
  const { data } = file;
  versionName.value = data.versionName;
  apkLink.value = data.relative_path;
  const size = Number(parseFloat(data.size / 1024 / 1024).toFixed(2));
  formRef.value.setFormData({ size, link: apkLink.value });
};

const onError = (error: Error) => {
  console.log(error);
  ElMessage.error(t("device_update.upload_error"));
  loading.value = false;
};

const editDisabled = () => {};

const formChange = ({ key, value }) => {
  if (key === "device_type") {
    formRef.value.setFormData({
      board_version: [],
      type: ""
    });
    borderVersionSet(value);
  }
};

const handleConfirm = () => {
  if (loading.value) {
    ElMessage.warning(t("device_update.uploading_warning"));
    return;
  }
  const data = cloneDeep(formRef.value.getFormData());
  let service = null;

  data.boards = isArray(data.board_version) ? data.board_version.join(",") : "";

  if (data.id) {
    service = softwareUpgradeUpdate;
  } else {
    service = softwareUpgradeAdd;
    data.is_force = false;
  }
  data.hiddenDeviceType = true;
  data.link = apkLink.value;
  service(omit(data, ["board_version"])).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: data.id
          ? t("device_update.edit_success")
          : t("device_update.add_success"),
        type: "success"
      });
      emit("update:modelValue", false);
      emit("submit");
    }
  });
};

const businessSet = () => {
  businessGetList({ size: 0 }).then(res => {
    formRef.value.setFormProps("business_id", { options: res.data });
  });
};

const borderVersionSet = (device_type: string) => {
  getBoardVersions({ size: 0, device_type, hiddenDeviceType: true }).then(
    res => {
      formRef.value.setFormProps("board_version", { options: res.data });
    }
  );

  formRef.value.setFormProps("type", {
    options: SOFTWARE_TYPES.filter(v => v.type === device_type)
  });
};
// endregion

watch(
  () => [showModal.value, props.formData],
  ([val, row]: [boolean, SoftwareUpgradeListProps]) => {
    if (val) {
      // debugger;
      title.value = row?.id
        ? t("device_update.modal.edit_title")
        : t("device_update.modal.title");
      businessSet();
      if (row?.id) {
        // selfFormData.value = rowData;
        nextTick(async () => {
          formRef.value.setFormData(row);
          selfFormData.value = {
            upgrade_type: row.upgrade_type,
            use_test: row.use_test,
            version_name: row.version_name
          };
          apkLink.value = row?.link;
          versionName.value = row?.version_name;

          if (row?.boards) {
            borderVersionSet(row?.device_type);
            formRef.value.setFormData({
              board_version: row?.boards?.split(",")
            });
          }

          formRef.value.setFormProps("type", {
            options: SOFTWARE_TYPES.filter(v => v.type === row?.device_type)
          });
        });
      }
      editDisabled();
    } else {
      formRef.value.setFormProps("type", {
        options: []
      });
      formRef.value.reset();
      apkLink.value = "";
      versionName.value = "";
      selfFormData.value = {
        upgrade_type: 0,
        use_test: 2,
        version_name: ""
      };
    }
  }
);
</script>
<style scoped lang="scss">
.upload-empDocs {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 2px;

  &::before {
    position: absolute;
    inset: 0;
    pointer-events: none; /* 确保伪元素不会影响鼠标事件 */
    content: "";
    border: 2px dashed var(--autata-border-color);
    transition: border-color 0.3s ease; /* 平滑过渡边框颜色 */
  }

  &:hover::before {
    border-color: var(--el-color-primary);
  }

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
    color: var(--el-color-primary);

    .iconfont {
      display: block;
      margin: 0 auto;
      font-size: 24px;
    }
  }
}
</style>
